﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HanGu.Services.Interface;
using HanGu.Entity;
using System.Web.Mvc;

namespace HanGu.Services
{
    public class ManagerService : BaseService, IManager
    {

        public List<Manager> GetAll()
        {
            using (HaiGuEntities obj = new HaiGuEntities())
            {
                var managers = obj.Manager.Where(c => c.Status != 0).OrderBy(k => k.User).ToList();
                foreach (var item in managers)
                {
                    item.Parents = obj.vwManager.Where(j => j.ManagerID == item.ID).ToList();
                }
                //managers = managers.Select(c =>
                //{
                //    return new Manager()
                //    {
                //        User = c.RealName + c.User,
                //        Age = c.Age,
                //        CreateTime = c.CreateTime,
                //        Creator = c.Creator,
                //        ID = c.ID,
                //        InWorkDate = c.InWorkDate,
                //        IsDirectly = c.IsDirectly,
                //        OutWorkDate = c.OutWorkDate,
                //        Parent = c.Parent,
                //        Position = c.Position,
                //        Pwd = c.Pwd,
                //        RealName = c.RealName,
                //        RoleID = c.RoleID,
                //        Sex = c.Sex,
                //        Status = c.Status,
                //        Parents = c.Parents
                //    };
                //}).ToList();
                return managers;
            }
        }

        string GenerateLevlSign(int level)
        {
            string splitSign = "├";
            for (int i = 0; i < level; i++)
            {
                splitSign += "─";
            }
            return splitSign;
        }
        //List<Manager> GetSons(List<Manager> Managers, int? parentID, int level)
        //{
        //    List<Manager> tmpSons = new List<Manager>();
        //    string splitSign = GenerateLevlSign(level);

        //    var tmpManagers = parentID.HasValue ? Managers.Where(c => c.Parent == parentID).ToList() :
        //        Managers.Where(c => !c.Parent.HasValue || c.Parent == 0).ToList();
        //    foreach (var tmpItem in tmpManagers)
        //    {
        //        tmpItem.User = string.Format("{0}{1}", splitSign, tmpItem.User);
        //        tmpSons.Add(tmpItem);
        //        List<Manager> tmpSons2 = new List<Manager>();
        //        tmpSons2 = GetSons(Managers, tmpItem.ID, level + 1).ToList();
        //        tmpSons.AddRange(tmpSons2);
        //    }
        //    return tmpSons;
        //}
        public List<Manager> GetAllByLevel(int? parentID = null, bool isLevel = true)
        {
            List<Manager> managersLevel = new List<Manager>();
            //if (!parentID.HasValue)
            {
                var allManagers = GetAll().Where(c => c.Status != 0)
                                    .Select(c =>
                                    {
                                        return new Manager()
                                        {
                                            User = c.RealName + c.User,
                                            Age = c.Age,
                                            CreateTime = c.CreateTime,
                                            Creator = c.Creator,
                                            ID = c.ID,
                                            InWorkDate = c.InWorkDate,
                                            IsDirectly = c.IsDirectly,
                                            OutWorkDate = c.OutWorkDate,
                                            Parent = c.Parent,
                                            Position = c.Position,
                                            Pwd = c.Pwd,
                                            RealName = c.RealName,
                                            RoleID = c.RoleID,
                                            Sex = c.Sex,
                                            Status = c.Status,
                                            Parents = c.Parents
                                        };
                                    }).ToList();
                if (parentID.HasValue)
                {
                    using (HaiGuEntities obj = new HaiGuEntities())
                    {
                        var sonIDs = obj.ManagerRelation.Where(c => c.ParentID == parentID).Select(c => c.ManagerID).ToList<int>();
                        sonIDs.Add(parentID.Value);
                        allManagers = allManagers.Where(c => sonIDs.Contains(c.ID)).ToList();
                    }
                }
                managersLevel.AddRange(allManagers);
            }
            //else
            //{
            //    using (HaiGuEntities obj = new HaiGuEntities())
            //    {
            //        var sonID = obj.ManagerRelation.Where(c => c.ParentID == parentID).Select(c => c.ManagerID);
            //        var relatePanrents = obj.Manager.Where(c => (sonID.Contains(c.ID) || c.ID == parentID) && c.Status != 0).ToList();
            //        relatePanrents = relatePanrents.Select(c =>
            //                        {
            //                            return new Manager()
            //                            {
            //                                User = c.RealName + c.User,
            //                                Age = c.Age,
            //                                CreateTime = c.CreateTime,
            //                                Creator = c.Creator,
            //                                ID = c.ID,
            //                                InWorkDate = c.InWorkDate,
            //                                IsDirectly = c.IsDirectly,
            //                                OutWorkDate = c.OutWorkDate,
            //                                Parent = c.Parent,
            //                                Position = c.Position,
            //                                Pwd = c.Pwd,
            //                                RealName = c.RealName,
            //                                RoleID = c.RoleID,
            //                                Sex = c.Sex,
            //                                Status = c.Status,
            //                                Parents = c.Parents
            //                            };
            //                        }).ToList();
            //        managersLevel.AddRange(relatePanrents);
            //    }
            //}
            return managersLevel;
        }
        public List<Manager> GetAll(UniversallySearchParam searchparma)
        {
            using (HaiGuEntities obj = new HaiGuEntities())
            {
                var query = obj.Manager.Where(c => (c.Status.HasValue && c.Status != -1 ? true : !c.Status.HasValue ? true : false));
                //query = query.Where(c => !Common.Helper.SuperUsers.Contains(c.User));
                if (searchparma.OnlySon.HasValue)
                {
                    var sonID = obj.ManagerRelation.Where(c => c.ParentID == searchparma.OnlySon).Select(c => c.ManagerID);
                    query = query.Where(c => sonID.Contains(c.ID) || c.ID == searchparma.OnlySon.Value); //仅看下属
                }
                if (!string.IsNullOrEmpty(searchparma.Ttile))
                {
                    query = query.Where(c => c.User.IndexOf(searchparma.Ttile) >= 0); //用户账号
                }
                if (!string.IsNullOrEmpty(searchparma.Suitabler))//真实姓名
                {
                    query = query.Where(c => c.RealName.IndexOf(searchparma.Suitabler) >= 0);
                }

                if (searchparma.IntObj2.HasValue)//用户状态
                {
                    query = query.Where(c => c.Status == searchparma.IntObj2);
                }
                if (searchparma.ClassType.HasValue)//角色
                {
                    query = query.Where(c => c.RoleID == searchparma.ClassType);
                }
                if (searchparma.StarDateTime.HasValue)
                {
                    query = query.Where(c => c.InWorkDate >= searchparma.StarDateTime);
                }
                if (searchparma.EndDateTime.HasValue)
                {
                    query = query.Where(c => c.InWorkDate <= searchparma.EndDateTime);
                }
                query = base.Paging<Manager, DateTime?>(c => c.InWorkDate, query, searchparma.Pagination);
                foreach (var item in query)
                {
                    item.Parents = obj.vwManager.Where(c => c.ManagerID == item.ID).ToList();
                }
                return query.ToList();
            }
        }

        public Manager GetByID(int id)
        {
            using (HaiGuEntities obj = new HaiGuEntities())
            {
                var model = obj.Manager.Where(c => c.ID == id).FirstOrDefault();
                if (model != null)
                {
                    model.Parents = obj.vwManager.Where(c => c.ManagerID == model.ID).ToList();
                    model.Parents = model.Parents ?? new List<vwManager>();
                }
                return model;
            }
        }

        public Manager GetByUser(string user)
        {
            using (HaiGuEntities obj = new HaiGuEntities())
            {
                var model = obj.Manager.Where(c => c.User == user).FirstOrDefault();
                if (model != null)
                {
                    model.Parents = obj.vwManager.Where(c => c.ManagerID == model.ID).ToList();
                    model.Parents = model.Parents ?? new List<vwManager>();
                }
                return model;
            }
        }

        public CurrentUserDTO GetByUserAndRoles(string user)
        {
            using (HaiGuEntities obj = new HaiGuEntities())
            {
                CurrentUserDTO userDTO = new CurrentUserDTO();
                var manager = obj.Manager.Where(c => c.User == user).FirstOrDefault();
                if (manager != null)
                {
                    userDTO.CurrentUserInfo = manager;
                    userDTO.UserName = user;
                    userDTO.Roles = this.GetRoles(manager.RoleID.Value);
                    var sonID = obj.ManagerRelation.Where(c => c.ParentID == manager.ID).Select(c => c.ManagerID);
                    userDTO.SubManager = obj.Manager.Where(c => sonID.Contains(c.ID) || c.ID == manager.ID).ToList();
                    userDTO.SubManager = userDTO.SubManager ?? new List<Manager>();
                    userDTO.SubManager = userDTO.SubManager.Where(c => c.ID != manager.ID).ToList();
                }

                return userDTO;
            }
        }

        public bool Add(Manager model)
        {
            try
            {
                using (HaiGuEntities obj = new HaiGuEntities())
                {
                    obj.Manager.AddObject(model);
                    obj.SaveChanges();
                    if (!string.IsNullOrEmpty(model.Parent))
                    {
                        bool isAdd = false;
                        foreach (var item in model.Parent.Split(','))
                        {
                            int parentid = 0;
                            if (int.TryParse(item, out parentid))
                            {
                                var rModel = new ManagerRelation()
                                {
                                    ManagerID = model.ID,
                                    ParentID = parentid,
                                    CreateTime = model.CreateTime,
                                    Creator = model.Creator
                                };
                                obj.ManagerRelation.AddObject(rModel);
                                isAdd = true;
                            }
                        }
                        if (isAdd)
                        {
                            obj.SaveChanges();
                        }
                    }
                    return true;
                }
            }
            catch { return false; }
        }

        public bool Update(Manager model)
        {
            try
            {
                using (HaiGuEntities obj = new HaiGuEntities())
                {
                    this.Update<Manager>(model);
                    string sql = string.Format("Delete from ManagerRelation WHERE ManagerID =({0})", model.ID);
                    obj.ExecuteStoreCommand(sql);
                    if (!string.IsNullOrEmpty(model.Parent))
                    {
                        //Delete<ManagerRelation>(c=>c.ManagerID==model.ID);                       
                        bool isAdd = false;
                        foreach (var item in model.Parent.Split(','))
                        {
                            int parentid = 0;
                            if (int.TryParse(item, out parentid))
                            {
                                var rModel = new ManagerRelation()
                                {
                                    ManagerID = model.ID,
                                    ParentID = parentid,
                                    CreateTime = model.CreateTime,
                                    Creator = model.Creator
                                };
                                obj.ManagerRelation.AddObject(rModel);
                                isAdd = true;
                            }
                        }
                        if (isAdd)
                        {
                            obj.SaveChanges();
                        }
                    }
                    return true;
                }
            }
            catch { return false; }
        }

        public bool Delete(int id)
        {
            try
            {
                this.Delete<Manager>(c => c.ID == id);
                return true;
            }
            catch { return false; }
        }

        public bool IsLogin(string user, string pwd)
        {
            try
            {
                using (HaiGuEntities obj = new HaiGuEntities())
                {
                    var manager = obj.Manager.Where(c => c.User == user && c.Pwd == pwd && c.Status == 10).SingleOrDefault();
                    if (manager != null)
                    { return true; }
                    else
                    { return false; }
                }

            }
            catch { return false; }
        }

        public bool MoveMember(string selectedMembers, string managerIDs, int? sourceManagerID = null)
        {
            try
            {
                using (HaiGuEntities obj = new HaiGuEntities())
                {
                    string sql = "UPDATE MemberInfo SET IsNew=1 WHERE ID in({0});";
                    string delSql = "Delete from MemberAssigned WHERE MemberID in({0})";
                    if (sourceManagerID.HasValue)
                    { delSql += string.Format(" and (ManagerID in ({0}) or ManagerID={1})", managerIDs, sourceManagerID.Value); }
                    sql += delSql;
                    sql = string.Format(sql, selectedMembers);
                    obj.ExecuteStoreCommand(sql);
                    //保存所属
                    if (!string.IsNullOrEmpty(selectedMembers))
                    {

                        foreach (var itemManager in managerIDs.Split(','))
                        {
                            int managerid = 0;
                            if (int.TryParse(itemManager, out managerid))
                            {
                                if (!string.IsNullOrEmpty(managerIDs))
                                {
                                    foreach (var itemMember in selectedMembers.Split(','))
                                    {
                                        int memberid = 0;
                                        if (int.TryParse(itemMember, out memberid))
                                        {
                                            var memberAssigned = new MemberAssigned() { MemberID = memberid, ManagerID = managerid };
                                            obj.MemberAssigned.AddObject(memberAssigned);

                                            var memberAssignedhis = new MemberAssignedHis() { MemberID = memberid, ManagerID = managerid, CreateDate = DateTime.Now };
                                            obj.MemberAssignedHis.AddObject(memberAssignedhis);

                                        }
                                    }
                                }
                            }
                        }
                        obj.SaveChanges();
                    }
                    return true;
                }

            }
            catch { return false; }
        }

        private List<VRolePurview> GetRoles(int roleID)
        {
            using (HaiGuEntities obj = new HaiGuEntities())
            {
                return obj.VRolePurview.Where(c => c.RoleID == roleID).ToList();
            }
        }
    }
}
